package com.link.base.base.order.controller;

import com.link.base.base.order.model.ArrivalDetails;
import com.link.base.base.order.model.SaleOrderItem;
import com.link.base.base.order.service.SaleOrderItemService;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.ServiceException;
import com.link.core.cllog.LCLogger;
import com.link.core.util.UserUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author unknown
 * @date unknown
 * @comments 定单行请求处理
 */
@Controller
@RequestMapping("/link/saleorderitem")
public class SaleOrderItemController extends BasicController<SaleOrderItem> {
    private static final Logger logger = LogManager.getLogger(SaleOrderItemController.class);
    @Resource
    private SaleOrderItemService saleOrderItemService;

    @Override
    public BasicService<SaleOrderItem> getBasicService() throws Exception {
        return saleOrderItemService;
    }

    @Override
    public void beforQueryExample(SaleOrderItem entity, HttpServletRequest request) throws Exception {
        super.beforQueryExample(entity, request);
        List<Filter> filters = entity.getQps().getFilters();
        boolean hashHeadIdFilter = filters.stream().anyMatch(f -> "headId".equals(f.getProperty()));
        if (entity.getHeadId() == null && !hashHeadIdFilter) {
            // 物料大类
            Long headId = Long.parseLong(request.getParameter("headId"));
            entity.setHeadId(headId == null ? Long.parseLong("noMatchId") : headId);
        }
    }

    @RequestMapping(value = "/qtyUpdate", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> qtyUpdate(@JsonParam SaleOrderItem entity, HttpSession session, HttpServletRequest request,
                                         HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            beforUpdate(entity, request);
            beforUpsert(entity, request);
            checkData(entity, request);
            String base = "base";
            if (!checkExistDataCache( base, session, entity)) {
                throw new ServiceException("PUBLIC-002");
            }
            saleOrderItemService.qtyUpdate(entity);
            result.put("newRow", saleOrderItemService.queryById(entity));
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>
     * 插入促销订单行
     * </p>
     *
     * @author yrf
     * @param list
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/insertPcyOrderItem", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> insertPcyOrderItem(@RequestBody List<SaleOrderItem> list, HttpSession session,
                                                  HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            Long acctId = user.getAcctId();
            if (acctId == null) {
                throw new ServiceException("ORDER-050");
            }
            if (list.size() <= 0) {
                throw new ServiceException("ORDER-085");
            }
            saleOrderItemService.insertPcyOrderItem(list);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 统计销量
     *
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/cumulateSale", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> cumulateSale(SaleOrderItem entity, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<SaleOrderItem> prodIdList = saleOrderItemService.querylistByOrderId(entity.getOrderId());
            String addStr = "add";
            if (addStr.equals(entity.getOrderStatus())) {
                for (SaleOrderItem saleOrderItem : prodIdList) {
                    if (saleOrderItem.getCumulateSale() != null && Integer.parseInt(saleOrderItem.getCumulateSale()) >= 0) {
                        saleOrderItem.setCumulateSale((Integer.parseInt(saleOrderItem.getCumulateSale()) + 1) + "");
                    } else {
                        saleOrderItem.setCumulateSale("1");
                    }
                    saleOrderItemService.prodCumulateSale(saleOrderItem);
                }
            } else {
                //"sub".equals(entity.getOrderStatus())
                for (SaleOrderItem saleOrderItem : prodIdList) {
                    if (saleOrderItem.getCumulateSale() != null && Integer.parseInt(saleOrderItem.getCumulateSale()) > 0) {
                        saleOrderItem.setCumulateSale((Integer.parseInt(saleOrderItem.getCumulateSale()) - 1) + "");
                    } else {
                        saleOrderItem.setCumulateSale("0");
                    }
                    saleOrderItemService.prodCumulateSale(saleOrderItem);
                }
            }
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询货到列表
     *
     * @param arrivalDetails
     * @return
     */
    @RequestMapping(value = "/queryArriDetailsByPage", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryArriDetailsByPage(@JsonParam QueryParams qps, @JsonParam ArrivalDetails arrivalDetails) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            ArrivalDetails ad = (ArrivalDetails) BasicModel.transformClass(arrivalDetails, qps);
            List<ArrivalDetails> list = saleOrderItemService.queryArriDetailsByPage(ad);
            result.put("rows", list);
            result.put("success", true);
            result.put("total", getCount((BasicModel) ad, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("message", e.getMessage());
            result.put("success", false);
        }
        return result;
    }

    /**
     * @author lizt
     * 20171009
     * 查询当前登录导购某天产品销售情况
     */
    @RequestMapping(value = "/querySaleProduct", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> queryOrderAmountBoard(SaleOrderItem record, HttpSession session,
                                                     HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<SaleOrderItem> list = saleOrderItemService.querySaleProduct(record);
            result.put("result", list);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @RequestMapping({"/batchDelete"})
    @ResponseBody
    public Map<String, Object> batchDelete(@RequestBody List<SaleOrderItem> list, HttpSession session,
                                           HttpServletRequest request, HttpServletResponse response) {
        HashMap result = new HashMap();

        try {
            SaleOrderItem entity = null;
            for (int i = 0; list != null && i < list.size(); ++i) {
                entity = (SaleOrderItem)list.get(i);
                this.beforDelete(entity, request);
                this.checkData(entity, request);
                if (!this.checkExistDataCache("base", session, entity)) {
                    throw new ServiceException("PUBLIC-031");
                }
            }

            this.getBasicService().batchDelete(list);
            result.put("success", true);
        } catch (BasicServiceException var8) {
            logger.error("BasicController捕获异常: ", var8);
            result.put("success", false);
            result.put("result", var8.getMessage());
            result.put("detailMessage", var8.getDetailMessage());
        } catch (Exception var9) {
            logger.error("BasicController捕获异常: ", var9);
            result.put("success", false);
            result.put("result", var9.getMessage());
        }

        return result;
    }
}
